<template>
	<view class="content">
		<text class="title">瓶子猜猜猜</text>
		<!-- 瓶子的容器 -->
		<view class="bot_container">
			<!-- 上面一排 -->
			<view class="bot_top">
				<view 
					class="top_container" 
					v-for="(item, index) in colors" 
					:key="index"
					:data-index="index"
					:data-source="'top'"
					@touchstart="startDrag($event, index, 'top')"
					@touchmove="onDrag($event)"
					@touchend="endDrag"
					:class="{ 
						'dragging': dragIndex === index && dragSource === 'top',
						'target': targetIndex === index && targetSource === 'top' && dragIndex !== -1
					}"
					:style="getDragStyle(index)"
				>
					<image ref="isbottle" :style="bgcolor(item)" src="../../static/bottle.svg"></image>
				</view>	
			</view>
			<!-- 下面一排 使用一张图片代替是假的。 -->
			<view class="bot_bottom">
				<view 
					class="bot_container" 
					v-for="(item, index) in shuffledColors" 
					:key="index"
					:data-index="index"
					:data-source="'bottom'"
				>
					<image :style="bgcolor(item)" src="../../static/bottle.svg"></image>
				</view>
			</view>
		</view>
		<!-- 提示和倒计时 -->
		<view class="bot_text">
			<view class="prompt">对了{{correctCount}}个</view>
			<view class="countdown">
				倒计时：{{countdown}}
			</view>
		</view>
		<view class="bottom_btn">
			<button @click="restart" class="restart-btn">重新开始</button>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'

// const botList = ref([])
let colors = ref([])
let shuffledColors = ref([])
const dragIndex = ref(-1) // 当前拖拽的索引
const dragSource = ref('') // 拖拽来源 'top' 或 'bottom'
const targetIndex = ref(-1) // 目标位置索引
const targetSource = ref('') // 目标位置来源
const countdown = ref(60) // 倒计时60秒
let timer = null
let startX = 0
let startY = 0
let currentX = 0
let currentY = 0
let offsetX = 0
let offsetY = 0
let bottlePositions = ref([]) // 存储每个瓶子的初始位置

// 计算正确的数量
const correctCount = computed(() => {
    let count = 0
    for (let i = 0; i < colors.value.length; i++) {
        if (colors.value[i] === shuffledColors.value[i]) {
            count++
        }
    }
    return count
})

function getRandomColor(count){
  const colors = [];
  
  // 生成count个均匀分布的色相
  for (let i = 0; i < count; i++) {
    // 将色环(360度)均匀分割
    const hue = Math.floor((i * 360) / count);
    // 使用固定的饱和度和亮度
    const saturation = 90;
    const lightness = 55;
    
    colors.push(`hsl(${hue}, ${saturation}%, ${lightness}%)`);
  }
  
  // 打乱颜色顺序，使其看起来更随机
  return shuffleArray(colors);
}
function bgcolor(bgcolor){
	return `width: 50px; height: 100px;background-color:${bgcolor}`
}
// 打乱数组
function shuffleArray(array){
	const newArray = [...array];
	for(let i = newArray.length - 1; i > 0;i--){
		const j = Math.floor(Math.random() * (i+1));
		[newArray[i], newArray[j]] =  [newArray[j], newArray[i]];
	}
	return newArray;
}

function initializeBlocks(){
	// 生成5个随机颜色
	colors.value =getRandomColor(5);
	// 生成的颜色再次进行洗牌
    shuffledColors.value = shuffleArray(colors.value);
	
	// 启动倒计时
	startCountdown()
    
    // 获取瓶子的初始位置
    setTimeout(() => {
        getBottlePositions()
    }, 100)
}

// 获取所有瓶子的初始位置
function getBottlePositions() {
    uni.createSelectorQuery()
        .selectAll('.top_container')
        .boundingClientRect(rects => {
            if (!rects) return
            bottlePositions.value = rects.map(rect => ({
                left: rect.left,
                top: rect.top,
                width: rect.width,
                height: rect.height
            }))
        })
        .exec()
}

// 获取拖拽样式
function getDragStyle(index) {
    if (index === dragIndex.value && dragSource.value === 'top') {
        return {
            position: 'fixed',
            left: `${currentX - offsetX}px`,
            top: `${currentY - offsetY}px`,
            zIndex: 1000
        }
    }
    return {}
}

// 开始拖拽
function startDrag(event, index, source) {
    // 只允许拖动第一排的瓶子
    if (source === 'top') {
        dragIndex.value = index
        dragSource.value = source
        
        // 记录起始触摸点
        const touch = event.touches[0]
        startX = touch.clientX
        startY = touch.clientY
        currentX = touch.clientX
        currentY = touch.clientY
        
        // 计算触摸点与瓶子左上角的偏移量
        if (bottlePositions.value[index]) {
            offsetX = touch.clientX - bottlePositions.value[index].left
            offsetY = touch.clientY - bottlePositions.value[index].top
        } else {
            offsetX = 0
            offsetY = 0
        }
    }
}

// 拖拽中
function onDrag(event) {
    if (dragIndex.value === -1) return
    
    const touch = event.touches[0]
    currentX = touch.clientX
    currentY = touch.clientY
    
    // 使用uni.createSelectorQuery查找目标元素
    uni.createSelectorQuery()
        .selectAll('.top_container')
        .boundingClientRect(rects => {
            if (!rects) return
            
            // 查找当前触摸点下的元素
            let found = false
            for (const rect of rects) {
                if (
                    currentX >= rect.left && 
                    currentX <= rect.right && 
                    currentY >= rect.top && 
                    currentY <= rect.bottom
                ) {
                    targetIndex.value = parseInt(rect.dataset.index)
                    targetSource.value = rect.dataset.source
                    found = true
                    break
                }
            }
            
            if (!found) {
                targetIndex.value = -1
                targetSource.value = ''
            }
        })
        .exec()
}

// 结束拖拽
function endDrag() {
    if (dragIndex.value !== -1 && targetIndex.value !== -1) {
        // 只允许在第一排内部交换
        if (dragSource.value === 'top' && targetSource.value === 'top') {
            // 上排内部交换
            const temp = colors.value[dragIndex.value]
            colors.value[dragIndex.value] = colors.value[targetIndex.value]
            colors.value[targetIndex.value] = temp
        }
        
        // 检查是否全部正确
        if (correctCount.value === colors.value.length) {
            clearInterval(timer)
            uni.showToast({
                title: '恭喜你，全部正确！',
                icon: 'success'
            })
        }
    }
    
    // 重置拖拽状态
    dragIndex.value = -1
    dragSource.value = ''
    targetIndex.value = -1
    targetSource.value = ''
    
    // 更新瓶子位置
    setTimeout(() => {
        getBottlePositions()
    }, 100)
}

// 重新开始游戏
function restart() {
    clearInterval(timer)
    countdown.value = 60
    initializeBlocks()
}

// 启动倒计时
function startCountdown() {
    clearInterval(timer)
    countdown.value = 60
    
    timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
            clearInterval(timer)
            uni.showToast({
                title: '时间到！是否重新开始游戏？',
                icon: 'none'
            })
        }
    }, 1000)
}

onMounted(()=>{
    console.log("这个是master分支的代码测试")
	initializeBlocks()
})

</script>

<style lang="scss" scoped>
	@import url('scss/index.scss');
</style>
